package demo24;


import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/*ReentrantLock可调用lockInterruptibly()方法，对线程的interrupt()方法作出响应，在一个线程等待的过程中，可以被打断。
 * ReentrantLock的lock()方法是不能被打断的，即锁用lock()方法锁定，线程调用interrupt()方法是毫无作用的*/
public class T {
    public static void main(String[] args) {
        Lock lock = new ReentrantLock();

        Thread t1 = new Thread(() -> {
            try {
                lock.lock();
                System.out.print("  t1 start...  ");
                TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);  //t1不停的运行，睡死了
                System.out.print("  t1 end...  ");
            } catch (InterruptedException e) {
                System.out.print(" t1-interrupted! ");
            } finally {
                System.out.println("t1 解锁");
                lock.unlock();
            }
        }, "t1");
        t1.start();

        Thread t2 = new Thread(() -> {
            try {
                 //lock.lock(); //不能对interrupt()方法作出响应
                 lock.lockInterruptibly();  //也是上锁，但是可以对interrupt()方法作出响应
                System.out.print("  t2 start...  ");
                TimeUnit.SECONDS.sleep(5);
                System.out.print("  t2 end...   ");
            } catch (InterruptedException e) {
                System.out.println("  t2-interrupted!  ");
            } finally {
                try {
                    System.out.println("t2 解锁");
                    lock.unlock();
                } catch (Exception e) {
                    System.out.println("没有得到锁的线程运行结束");
                }
            }
        }, "t2");
        t2.start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.interrupt();  //打断t2的等待，如果使用的是t2使用的是lock()方法进行上锁就无法打断，如果使用lockInterruptibl()方法就可以打断
    }

}

